package com.elinkway.infinitemovies.share;


import android.support.v4.app.FragmentActivity;
import android.webkit.JavascriptInterface;

import com.elinkway.infinitemovies.bean.ShareContent;
import com.elinkway.infinitemovies.utils.LogUtils;
import com.elinkway.infinitemovies.utils.UIs;
import com.umeng.socialize.bean.SHARE_MEDIA;

import org.json.JSONException;
import org.json.JSONObject;


public class ShareJavascriptInterface {
    private FragmentActivity mActivity;
    private ShareCommonPopWindow mPopWindow;
    public ShareJavascriptInterface(FragmentActivity mActivity,ShareCommonPopWindow popwindow) {
        super();
        this.mActivity = mActivity;
        this.mPopWindow = popwindow;
    }
    
    @JavascriptInterface
    public void toast(final String text) {
        mActivity.runOnUiThread(new Runnable() {

            @Override
            public void run() {
            	UIs.showToast(text);
            }
        });
    }
    @JavascriptInterface
    public void share(final String content, final String type) {
        LogUtils.d("lottery","share content: "+content+" type:"+type);
        mActivity.runOnUiThread(new Runnable() {

            @Override
            public void run() {

                try {
                    if (type.equals("all")){
                        if(null != mPopWindow){
                            mPopWindow.setShareContent(parseJson(content));
                            mPopWindow.show();
                        }
                    } else if (type.equals("friends")) {
                        ShareUtils.shareToThird(mActivity, parseJson(content), SHARE_MEDIA.WEIXIN_CIRCLE);
                    } else if (type.equals("qzone")) {
                        ShareUtils.shareToThird(mActivity, parseJson(content), SHARE_MEDIA.QZONE);
                    } else if (type.equals("weibo")) {
                        ShareUtils.shareToThird(mActivity, parseJson(content), SHARE_MEDIA.SINA);
                    } else if(type.equals("qq")) {
                        ShareUtils.shareToThird(mActivity, parseJson(content), SHARE_MEDIA.QQ);
                    } else if(type.equals("weixin")) {
                        ShareUtils.shareToThird(mActivity, parseJson(content), SHARE_MEDIA.WEIXIN);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private ShareContent parseJson(String json) throws JSONException {
        ShareContent sc = new ShareContent();
        JSONObject data = new JSONObject(json);
        sc.setContent(data.getString("text"));
        sc.setLink(data.getString("link"));
        sc.setImageUrl(data.getString("img"));
        return sc;
    }
}
